<?php

namespace app\admins\controller;

class TestDbCurd extends Base
{
    // Curd 复用（Db类）
    use DbCurd;

    // 初始化
    protected function initialize()
    {
        $this->table = 'test'; //数据表名
        $this->pk = 'id'; //数据表主键
        $this->field = []; //查询字段
        $this->map = []; //初始条件
        $this->sort = ['id' => 'desc']; //排序
        $this->is_page = true; //是否分页
        $this->rule = [ //验证规则
            'id|ID' => 'require|number',
            'meta_key|键' => 'require|alphaDash|token|unique:test', // 验证token且值唯一
            'meta_value|值' => 'requireWith:meta_value|chsDash',
            'status|状态' => 'require|in:0,1',
        ];
        $this->allow_fields = [ //允许的字段
            'save' => ['meta_key', 'meta_value', 'status'],
            'save_edit' => ['id', 'meta_key', 'meta_value', 'status'],
            'modify' => ['meta_value', 'status'],
        ];

        $this->action = $this->request->action();
        if ($this->action === 'save') {
            $this->param = $this->request->param();
            $this->param['time'] = time();
        }
    }

    // 数据返回
    private function datas($datas)
    {
        $datas = $datas->map(function ($item) {
            // $item['status'] = $item['status'] ? '<span style="color:#c2c2c2">禁用</span>' : '<span style="color:#5FB878">启用</span>';
            $item['time'] = date('Y-m-d H:i:s', $item['time']);
            return $item;
        });
        return $datas;
    }
}
